package com.foryou.wechat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.foryou.wechat.common.Constants;
import com.foryou.wechat.common.enums.AuditStatusEnum;
import com.foryou.wechat.common.enums.CapacityEnum;
import com.foryou.wechat.entity.ProductionEntity;
import com.foryou.wechat.entity.UserBackgroundEntity;
import com.foryou.wechat.entity.UserEntity;
import com.foryou.wechat.entity.UserToken;
import com.foryou.wechat.mapper.*;
import com.foryou.wechat.model.Query;
import com.foryou.wechat.model.dto.UserDTO;
import com.foryou.wechat.model.vo.UserIndexVo;
import com.foryou.wechat.model.vo.UserInfoVo;
import com.foryou.wechat.service.UserFollowService;
import com.foryou.wechat.service.UserService;
import com.foryou.wechat.utils.EnumUtil;
import com.foryou.wechat.utils.HttpContextUtils;
import com.foryou.wechat.utils.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * Created by Lee.
 */
@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final UserFollowService userFollowService;
    private final UserImageMapper userImageMapper;
    private final UserTokenMapper userTokenMapper;
    private final UserBackMapper userBackMapper;
    private final ProductionMapper productionMapper;

    public UserServiceImpl(UserMapper userMapper, UserFollowService userFollowService, UserImageMapper userImageMapper, UserTokenMapper userTokenMapper, UserBackMapper userBackMapper, ProductionMapper productionMapper) {
        this.userMapper = userMapper;
        this.userFollowService = userFollowService;
        this.userImageMapper = userImageMapper;
        this.userTokenMapper = userTokenMapper;
        this.userBackMapper = userBackMapper;
        this.productionMapper = productionMapper;
    }

    @Override
    public Response userLogin(String openId, String nickname,
                                String avatarUrl, String gender,String sessionKey) {
        UserEntity entity = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("open_id", openId));
        if (ObjectUtils.isEmpty(entity)) {
            //添加
            entity = new UserEntity(nickname, avatarUrl, Integer.parseInt(gender),openId);
            //随机分配用户背景图片
            entity.setBackgroundUrl(getBackUrl());
            userMapper.insert(entity);
        }

        //生成唯一TOKEN
        UserToken userToken = userTokenMapper.selectById(entity.getId());
        if (userToken == null) {
            userTokenMapper.insert(new UserToken(entity.getId(), sessionKey, new Date()));
        }else {
            userToken.setLastTime(new Date());
            userToken.setToken(sessionKey);
            userTokenMapper.updateById(userToken);
        }
        return getUserInfo(entity.getId());
    }

    @Override
    public int updateUser(UserDTO userDTO) {
        int result = 0;
        try {
            result = userMapper.updateById(new UserEntity(
                    HttpContextUtils.getUserId(),
                    DateUtils.parseDate(userDTO.getBirthday(), Constants.DATE_FORMAT_PATTERN),
                    userDTO.getGender(),
                    userDTO.getRegion(),
                    userDTO.getProvince(),
                    userDTO.getCapacity(),
                    userDTO.getPhone(),
                    userDTO.getWeChat(),
                    userDTO.getWeibo()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

    @Override
    public boolean updateUserAvatar(Long userId,String url) {
        UserEntity userEntity = userMapper.selectById(userId);
        if (StringUtils.isEmpty(url)) {
            return false;
        }
        userEntity.setAvatarUrl(url);
        return userMapper.updateById(userEntity) > 0;
    }

    @Override
    public Response getUserIndex(Long userId) {
        //1.得到用户信息
        UserEntity userEntity = userMapper.selectById(userId);

        //2.得到用户作品信息数量
        int shootCount = productionMapper.selectCount(new QueryWrapper<ProductionEntity>()
                .eq("user_id", userId)
                .eq("audit_status", AuditStatusEnum.PASS.getCode()));
        //3.得到用户关注数量
        int followUserList = userFollowService.followUserList(userEntity.getId());
        //4.得到用户粉丝数量
        int fansUserList = userFollowService.fansUserList(userEntity.getId());

        return Response.success(new UserIndexVo(
                userEntity.getId(),userEntity.getNickname(),
                userEntity.getAvatarUrl(),
                EnumUtil.getEnumByCode(CapacityEnum.class,userEntity.getCapacity()),
                userEntity.getBackgroundUrl(),
                userEntity.getGender(),
                userEntity.getProvince(),
                shootCount,followUserList,fansUserList)
        );
    }

    @Override
    public Response getFollowList(int start,Long userId) {
        return userFollowService.getFollowUserList(start,userId);
    }

    @Override
    public Response getFansList(int start,Long userId) {
        return userFollowService.getFansUserList(start,userId);
    }

    @Override
    public Response getWorksImageList(int start,Long userId) {
        if (userId == 0) {
            userId = HttpContextUtils.getUserId();
        }
        List<String> imageList = userImageMapper.getUserImageList(start, userId);
        return Response.success(imageList);
    }

    @Override
    public Response updateUserBack(Long userId, String url) {
        UserEntity userEntity = userMapper.selectById(userId);
        if (userEntity == null) {
            return Response.failure(Constants.OPERATION_FAILURE);
        }
        userEntity.setBackgroundUrl(url);
        int update = userMapper.updateById(userEntity);
        return update>0?Response.success(url):Response.failure(Constants.OPERATION_FAILURE);
    }

    @Override
    public Response getUserInfo(Long userId) {
        UserEntity userEntity = userMapper.selectById(userId);
        String[] region = StringUtils.isBlank(userEntity.getRegion())?null:
                userEntity.getRegion().split(" ");
        String birthday = null == userEntity.getBirthday() ? "" : DateFormatUtils.format(userEntity.getBirthday(), Constants.DATE_FORMAT_PATTERN);
        return Response.success(
                new UserInfoVo(
                        userId,
                        userEntity.getNickname(),
                        userEntity.getAvatarUrl(),
                        birthday,
                        userEntity.getGender(),
                        region,
                        userEntity.getCapacity(),
                        userEntity.getPhone(),
                        userEntity.getWeChat(),
                        userEntity.getWeibo()
                )
        );
    }

    @Override
    public boolean checkUserInfo(Long userId) {
        UserEntity userEntity = userMapper.selectById(userId);
        if (userEntity.getCapacity() == 0|| StringUtils.isEmpty(userEntity.getRegion()) || StringUtils.isEmpty(userEntity.getPhone())) {
            return false;
        }
        return true;
    }

    private String getBackUrl() {
        List<UserBackgroundEntity> selectList = userBackMapper.selectList(new QueryWrapper<UserBackgroundEntity>()
                .eq("enabled", 1));
        if (CollectionUtils.isEmpty(selectList)) {
            return "";
        }
        int result = (int) ( Math.random() * (selectList.size()));
        return selectList.get(result).getUrl();
    }
}
